package bits;

/**
 * leet-code(461) 汉明距离
 *
 * @author Ringo
 * @date 2021/10/3 9:11
 */
public class HammingDistance {

    public static void main(String[] args) {
        int x = 3, y = 1;
        System.out.println(hammingDistance(x, y));
        System.out.println(hammingDistance1(x, y));
    }

    // 移位运算
    public static int hammingDistance(int x, int y) {
        int n = x ^ y;
        int count = 0;
        while (n != 0) {
            if ((n & 1) == 1) {
                ++count;
            }
            n >>>= 1;
        }
        return count;
    }


    // n & (n - 1) 是删除最右侧 1 之后的结果
    // (n & (n - 1)) == 0 表示 n 是 2 的幂
    public static int hammingDistance1(int x, int y) {
        int n = x ^ y;
        int count = 0;
        while (n != 0) {
            n = n & (n - 1);
            ++count;
        }
        return count;
    }
}
